import json
import os


STATE_PATH = './state/state.json'


def load_state() -> dict:
    try:
        if not os.path.exists(STATE_PATH):
            os.makedirs(os.path.dirname(STATE_PATH), exist_ok=True)
            with open(STATE_PATH, 'w', encoding='utf-8') as f:
                json.dump({"seq": 0}, f, ensure_ascii=False, indent=2)
        with open(STATE_PATH, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception:
        # 备份损坏文件
        try:
            if os.path.exists(STATE_PATH):
                os.replace(STATE_PATH, STATE_PATH + '.bak')
        finally:
            with open(STATE_PATH, 'w', encoding='utf-8') as f:
                json.dump({"seq": 0}, f, ensure_ascii=False, indent=2)
            return {"seq": 0}


def save_state(state: dict) -> None:
    os.makedirs(os.path.dirname(STATE_PATH), exist_ok=True)
    with open(STATE_PATH, 'w', encoding='utf-8') as f:
        json.dump(state, f, ensure_ascii=False, indent=2)


